"""
更新个体最优集pBest
"""

import numpy as np


def updatePBest(pBest, pFits, pops, fits):
    """
    Params:
        :param pBest: 上一步的种群中计算出来的局部最优
        :param pFits: 上一步的适应度函数
        :param pops: 坐标更新后的粒子群
        :param fits:pops坐标更新后重新计算的适应度
        :return:
    """
    nPop, nF = fits.shape
    # def dominates(X1, X2):
    #   if(np.any(X1 < X2) and np.all(X1 <= X2)):
    #       return True
    #   else:
    #       return False
    isDom1 = fits <= pFits
    isDom2 = fits < pFits
    isCh = (np.sum(isDom1, axis=1) == nF) & \
           (np.sum(isDom2, axis=1) >= 1)
    if np.sum(isCh) >= 1:
        # 种群中的解支配pBest的话更新pBest
        pBest[isCh] = pops[isCh]
        pFits[isCh] = fits[isCh]
    return pBest, pFits


if __name__ == "__main__":
    pBest = np.array([[0.1270048, -1.53662201, 1.85512328], [1.63856792, 1.60141118, -0.45428181]])
    pFits = np.array([[1, 2], [2, 2]])
    pops = np.array([[0.1270048, -1.53662201, 1.85512328], [1.63856792, 1.60141118, -0.45428181]])
    fits = np.array([[1, 1], [2, 1]])
    pBest, pFits = updatePBest(pBest, pFits, pops, fits)
    # 将pBest第一行的数据进行了替换
    # pBest-- [[ 0.1270048  -1.53662201  1.85512328]
    #  [ 1.63856792  1.60141118 -0.45428181]]
    print("pBest--", pBest)
    # pFits-- [[1 1]
    #  [2 1]]
    print("pFits--", pFits)
